package com.emex.app.stuff.utils;

import java.io.ByteArrayOutputStream;
import javax.swing.JTable;
import javax.swing.table.TableModel;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

/**
 *
 * @author Sergey Karavaev
 */
public class ExportUtils {

    public static byte[] exportToExcel(JTable table) throws Exception {
        Workbook wb = new HSSFWorkbook();
        Sheet sheet = wb.createSheet();
        Row row = null;
        Cell cell = null;
        TableModel model = table.getModel();
        for (int i = 0; i < model.getRowCount(); i++) {
            row = sheet.createRow(i);
            for (int j = 0; j < model.getColumnCount(); j++) {
                cell = row.createCell(j);
                cell.setCellValue(model.getValueAt(i, j).toString());
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        wb.write(baos);
        return baos.toByteArray();
    }

}
